package com.shujichen.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 任务执行策略配置
 */
@Slf4j
@Configuration
public class TaskConfig {

    /**
     * 执行模式: single:单线程, concurrent:多线程
     */
    @Value("${task.queue.mode}")
    private String executionMode;

    /**
     * 最大并发数, 仅在多线程模式下有效
     */
    private int maxConcurrent = Runtime.getRuntime().availableProcessors();

    @Bean
    public ThreadPoolExecutor taskExecutor() {
        if ("concurrent".equals(executionMode)) {
            log.info("==========当前任务执行策略为多线程, 并发线程数 {} ==========", maxConcurrent);
            return new ThreadPoolExecutor(
                    maxConcurrent, maxConcurrent,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>());
        } else {
            log.info("==========当前任务执行策略为单线程==========");
            return new ThreadPoolExecutor(
                    1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>());
        }
    }

}
